package com.zhipu.balance.utils

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Environment
import androidx.core.content.FileProvider
import com.blankj.utilcode.util.ActivityUtils
import java.io.File
import java.text.DecimalFormat
import java.util.Locale


object CommonUtils {


    /**
     * 保留两位小数，四舍五入的一个老土的方法
     * @param d
     * @return
     */
    fun formatDouble(d: Double?): Double {
        if (d.toString() == "Infinity" || d.toString() == "-Infinity" || d.toString() == "NaN") {
            return 0.00
        }else{
            var mDecimalFormat = DecimalFormat("#.00")
            var calculation = mDecimalFormat.format(d)
            return calculation.toDouble()
        }
    }


    fun chmod666(device: File?): Boolean {
        if (null == device || !device.exists()) {
            return false
        }
        try {
            val su = Runtime.getRuntime().exec("/system/xbin/su")
            var cmd = "chmod 666 ${device.absolutePath}\nexit\n"
            su.outputStream.write(cmd.toByteArray())
            if (0 == su.waitFor() && device.canRead() && device.canWrite() && device.canExecute()) {
                return true
            }
        }catch (e : Exception){
            e.printStackTrace()
        }
        return false
    }


    /**
     * 名称
     * @return
     */
    fun getApkName(): String? {
        val apkUrl = Environment.getExternalStorageDirectory().absolutePath
        var appName = apkUrl.substring(apkUrl.lastIndexOf("/") + 1, apkUrl.length)
        if (!appName.endsWith(".apk")) {
            appName = "Balance.apk"
        }
        return appName
    }





    fun ByteArray.toHexString(): String {
        return StringBuilder().run {
            this@toHexString.forEach {
                this.append(Integer.toHexString((it.toInt() and 0xFF or 0x100)).substring(1, 3))
            }
            this.toString().uppercase(Locale.ROOT)
        }
    }


    /**
     * install slient
     *
     * @param filePath
     * @return 0 means normal, 1 means file not exist, 2 means other exception error
     */
    fun installSilent(filePath: String?,mContext : Context): Int {
        val intent = Intent(Intent.ACTION_VIEW)
        val apkFile = File(filePath) // 替换成你要安装的 APK 文件路径
        val apkUri = FileProvider.getUriForFile(ActivityUtils.getTopActivity(), "com.zhipu.balance.fileprovider", apkFile)
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        intent.setDataAndType(apkUri, "application/vnd.android.package-archive")
        ActivityUtils.getTopActivity().startActivity(intent)
        return 0
    }
}